package com.leyou.page.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.dto.BrandDTO;
import com.leyou.dto.CategoryDTO;
import com.leyou.dto.SpecGroupDTO;
import com.leyou.dto.SpuDTO;
import com.leyou.item.client.ItemClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;


    public Map<String,Object> buildFilter(Long spuId){

        SpuDTO spuDTO = itemClient.findSpuBySpuId(spuId);
        BrandDTO brandDTO = itemClient.queryBrandById(spuDTO.getBrandId());
        List<CategoryDTO> categorys = itemClient.findByCategorysByIds(spuDTO.getCategoryIds());
        List<SpecGroupDTO> specGroupDTOS = itemClient.findSpecGroupWithParamsBuCid(spuDTO.getCid3());

        Map<String,Object> map  =  new HashMap<>();
        map.put("categories",categorys);
        map.put("brand",brandDTO);
        map.put("spuName",spuDTO.getName());
        map.put("subTitle",spuDTO.getSubTitle());
        map.put("detail",spuDTO.getSpuDetail());
        map.put("skus",spuDTO.getSkus());
        map.put("specs",specGroupDTOS);
        return map;
    }

    @Value("${ly.static.itemDir}") //模板生成地址
    private String itemDir;
    @Value("${ly.static.itemTemplate}") //模板名称
    private String itemTemplate;
    @Autowired
    private TemplateEngine templateEngine; //模板引擎


    public void buildStaticPage(Long spuId){
    //准备上下文
        Context context = new Context();
        context.setVariables(buildFilter(spuId));

        //指定静态页面在服务器中的地址 和名称
        File pageFile = new File(new File(itemDir),spuId+".html");

        try (PrintWriter printWriter = new PrintWriter(pageFile)) {
            //参数一 模板名称 参数二：上下文 参数三 ：输出流
            templateEngine.process(itemTemplate,context,printWriter);
        }catch (Exception e){
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
        }
    }

    //删除静态页面
    public void delStaticPage(Long spuId) {
        //指定静态页面在服务器中的地址 和名称
        File pageFile = new File(new File(itemDir),spuId+".html");
        //判断如果存在就删除
        if(pageFile.exists()){
            pageFile.delete();
        }
    }
}
